import React from 'react';
import './index.less';
import { Button, Modal } from 'antd';
import { connect } from 'umi';
import CommonForm from '@/components/form';
import CommonContain from '@/components/contain';
import CommonTable from '@/components/table';
import CommonDialog from '@/components/dialog';
import Search from '@/components/search';
import { ExclamationCircleOutlined } from '@ant-design/icons';

@connect(({ menu, loading }) => ({ menu, loading }))
export default class MenuList extends React.Component {
  constructor(props) {
    super(props);
    this.formRef = React.createRef();
    this.state = {
      dialogTitle: '新增菜单',
      optButtonType: null,
    };
  }

  componentWillMount() {
    this.props.dispatch({
      type: 'menu/list', //全局namespace/全局effects方法名
      payload: {}, //payload，参数
    });
  }

  componentDidMount() {}

  /**
   * 数据单元格操作
   * @param {*} optType 操作方式 edit-编辑 info-详情 delete-删除
   * @param {*} text
   * @param {*} record 行记录
   * @param {*} index 下标
   */
  rowHandleEvent = (optType, text, record, index) => {
    const that = this;
    const emnuOptTypeObj = {
      edit: '编辑菜单',
      info: '查看详情',
      delete: '删除',
    };
    const { menuParentId, menuPath, menuName, id } = record || {};
    this.setState({
      dialogTitle: emnuOptTypeObj[optType],
      optButtonType: optType,
    });

    if (optType === 'edit' || optType === 'info') {
      this.refs['common-dialog'].setIsModalVisible(true);
      // FIX 防止dialog刚开始展示时对象组件还没完全创建 防止无法找到对象
      setTimeout(() => {
        this.formRef.current.setFieldsValue(
          { menuParentId, menuPath, menuName, id },
          100,
        );
      });
    }
    if (optType == 'delete') {
      Modal.confirm({
        title: '提示?',
        icon: <ExclamationCircleOutlined />,
        content: '确认删除当前选中记录？',
        okText: '确认',
        okType: 'danger',
        cancelText: '关闭',
        onOk() {
          that.props.dispatch({
            type: 'menu/del',
            payload: { id },
          });
          this.refs['common-table'].loadTableList();
        },
        onCancel() {},
      });
    }
    console.log('rowHandleEvent', optType, text, record, index);
  };

  /**
   * 弹框关闭点击事件
   */
  dialogCancel = async () => {
    this.refs['common-dialog'].setIsModalVisible(false);
    this.setState({ dialogTitle: '新增菜单', optButtonType: null });
  };
  /**
   * 弹框确认点击事件
   */
  dialogOk = async () => {
    try {
      const values = await this.formRef.current.validateFields();
      console.log('Success:', values);
      this.props.dispatch({
        type: values.id ? 'menu/update' : 'menu/add',
        payload: values,
      });
      this.refs['common-table'].loadTableList();
      this.refs['common-dialog'].setIsModalVisible(false);
    } catch (errorInfo) {
      console.log('Failed:', errorInfo);
    }
  };

  /**
   * 按钮点击事件
   */
  defaultClick = (type, el, values) => {
    // console.log(this.refs['common-dialog']);
    console.log('type, el, values', type, el, values);
    if (type == 'add') {
      this.setState({ dialogTitle: '新增菜单' });
      this.refs['common-dialog'].setIsModalVisible(true);
      setTimeout(() => {
        this.formRef.current.setFieldsValue(
          { menuParentId: '', menuPath: '', menuName: '', id: '' },
          100,
        );
      });
    }
  };

  /**
   * 表格表头-列字段
   */
  buildColumns = () => {
    return [
      { fixed: 'left', width: 60, title: 'ID', dataIndex: 'id' },
      { width: 120, title: '菜单名称', dataIndex: 'menuName' },
      { width: 120, title: '菜单路径', dataIndex: 'menuPath' },
      { width: 120, title: '菜单父级ID', dataIndex: 'menuParentId' },
      { width: 160, title: '创建时间', dataIndex: 'createTime' },
      {
        title: '操作',
        fixed: 'right',
        dataIndex: '',
        width: 200,
        render: (text, record, index) => (
          <div>
            <Button
              type="link"
              onClick={() => this.rowHandleEvent('edit', text, record, index)}
            >
              修改
            </Button>
            <Button
              type="link"
              onClick={() => this.rowHandleEvent('info', text, record, index)}
            >
              详情
            </Button>
            <Button
              type="link"
              onClick={() => this.rowHandleEvent('delete', text, record, index)}
              danger
            >
              删除
            </Button>
          </div>
        ),
      },
    ];
  };
  /**
   * 查询条件-表单元素
   */
  buildQueryFormItem = () => {
    return [
      {
        formItem: {
          name: 'menuName',
          label: '菜单名称',
        },
        formElement: {
          'el-type': 'input',
          placeholder: '提示：请输入菜单名称',
        },
      },
    ];
  };
  /**
   * 新增｜详情｜修改表单元素
   */
  buildFormItem = () => {
    return [
      {
        formItem: {
          name: 'id',
          hidden: true,
        },
        formElement: {},
      },
      {
        formItem: {
          name: 'menuName',
          label: '菜单名称',
          rules: [
            {
              required: true,
              message: '请输入菜单名称',
            },
          ],
        },
        formElement: {
          'el-type': 'input',
          placeholder: '提示：请输入菜单名称',
        },
      },
      {
        formItem: {
          name: 'menuPath',
          label: '菜单路径',
          rules: [
            {
              required: false,
              message: '请输入菜单路径',
            },
          ],
        },
        formElement: {
          'el-type': 'input',
          placeholder: '提示：请输入菜单路径',
        },
      },
      {
        formItem: {
          name: 'menuParentId',
          label: '菜单父级ID',
          rules: [
            {
              required: true,
              message: '请输入菜单父级ID',
            },
          ],
        },
        formElement: {
          'el-type': 'input',
          placeholder: '提示：请输入菜单父级ID',
        },
      },
    ];
  };
  render() {
    const { dialogTitle, optButtonType } = this.state;
    const isDetail = optButtonType === 'info' ? true : false;
    return (
      <CommonContain>
        {/* 弹框新增/修改/详情 */}
        <CommonDialog
          ref="common-dialog"
          onOk={this.dialogOk}
          onCancel={this.dialogCancel}
          otherProps={{
            keyboard: false,
            maskClosable: false,
            cancelText: '关闭',
            okText: '确定	',
            title: dialogTitle,
            width: 500,
          }}
          extendProps={isDetail ? { footer: null } : {}}
        >
          {/* 公共表单 */}
          <CommonForm
            ref={this.formRef}
            formFileds={this.buildFormItem()}
            isDisabled={isDetail}
            otherProps={{
              layout: 'horizontal',
              labelCol: { span: 5 },
              wrapperCol: { span: 19 },
            }}
          />
          {/* 公共表单 */}
        </CommonDialog>
        {/* 弹框新增/修改/详情 */}
        {/* 查询条件区域 */}
        <Search
          formFileds={this.buildQueryFormItem()}
          defaultClick={this.defaultClick}
        />
        {/* 查询条件区域 */}
        {/* 列表区域 */}
        <CommonTable
          ref="common-table"
          url="/api/menus"
          columns={this.buildColumns()}
          rowKey="id"
        />
        {/* 列表区域 */}
      </CommonContain>
    );
  }
}

// export default (props) => {
//   return <Button>DEMO</Button>
// }
